package com.coincalf.service.impl;

import com.coincalf.dto.WithdrawAddressDTO;
import com.coincalf.entity.Coin;
import com.coincalf.entity.UserWallet;
import com.coincalf.framework.enums.BaseStatus;
import com.coincalf.framework.exception.GlobalDefaultException;
import com.coincalf.mapper.UserWalletMapper;
import com.coincalf.service.CoinService;
import com.coincalf.service.UserWalletService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.coincalf.user.feign.UserServiceClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * <p>
 * 用户钱包表 服务实现类
 * </p>
 *
 * @author qiang
 * @since 2018-05-12
 */
@Service
@Slf4j
public class UserWalletServiceImpl extends ServiceImpl<UserWalletMapper, UserWallet> implements UserWalletService {

    @Autowired
    private CoinService coinService;
    @Autowired
    private UserServiceClient userServiceClient;

    /**
     * 添加提币地址
     *
     * @param withdrawAddress
     * @param userId          用户ID
     * @return
     */
    @Override
    public void addAddress(WithdrawAddressDTO withdrawAddress, Long userId) {
        UserWallet userWallet = new UserWallet();
        userWallet.setUserId(userId);
        userWallet.setAddr(withdrawAddress.getAddress());
        userWallet = baseMapper.selectOne(userWallet);
        if (userWallet != null) {
            throw new GlobalDefaultException(60000);
        }

        /*UserDTO user = userServiceClient.selectById(userId);
        if (!StringUtils.isNotEmpty(user.getPaypassword()) || !new BCryptPasswordEncoder().matches(withdrawAddress.getPayPassword(), user.getPaypassword())) {
            log.error("资金交易密码错误");
            throw new GlobalDefaultException(50020);
        }*/
        userWallet = new UserWallet();
        Coin coin = coinService.queryById(withdrawAddress.getCoinId());
        if (coin != null) {
            userWallet.setAddr(withdrawAddress.getAddress())
                    .setCoinId(withdrawAddress.getCoinId())
                    .setCoinName(coin.getName())
                    .setUserId(userId)
                    .setName(withdrawAddress.getName())
                    .setSort(0)
                    .setStatus(BaseStatus.EFFECTIVE.getCode())
                    .setLastUpdateTime(new Date())
                    .setCreated(new Date());
            baseMapper.insert(userWallet);
        } else {
            throw new GlobalDefaultException(2029);
        }
    }

    @Override
    public boolean selectExist(Long userId, Long coinId, String address) {
        UserWallet userWallet = new UserWallet();
        userWallet.setUserId(userId);
        userWallet.setCoinId(coinId);
        userWallet.setAddr(address);
        return baseMapper.selectOne(userWallet) != null;
    }

}
